package org.dragon.models;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Author:     Zhao Yan
 * DateTime:   2023/5/18 9:02
 */
public class RedisSessionAccount {

    public Account account;

    public Credential credential;

    public RedisSessionEmail email;

    public List<RedisSessionRole> roles = new ArrayList<>();

    public boolean check(String[] targetRoles, String[] targetPermissions) {
        return checkRoles(targetRoles) && checkPermissions(targetPermissions);
    }

    public boolean checkPermissions(String[] targetPermissions) {
        Set<String> ps = new HashSet<>();

        for (RedisSessionRole role : roles)
            for (Permission permission : role.permissions)
                if (permission != null)
                    ps.add(permission.getCode());

        for (String targetPermission : targetPermissions)
            if (!ps.contains(targetPermission))
                return false;

        return true;
    }

    private boolean checkRoles(String[] targetRoles) {
        if (targetRoles == null)
            return true;

        for (String targetRole : targetRoles) {
            boolean exits = false;

            for (RedisSessionRole r : roles) {
                if (r.role.getCode().equals(targetRole)) {
                    exits = true;
                    break;
                }
            }

            if (!exits)
                return false;
        }

        return true;
    }

    @Override
    public String toString() {
        return "RedisSessionAccount{" +
                "account=" + account +
                ", credential=" + credential +
                ", email=" + email +
                '}';
    }
}
